package com.xiaoshuidi.cloud.module.member.service.user;

import cn.hutool.core.lang.Assert;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.module.member.controller.app.auth.vo.AppAuthSmsSendReqVO;
import com.xiaoshuidi.cloud.module.member.framework.sms.SmsCodeProperties;
import com.xiaoshuidi.cloud.module.system.enums.sms.SmsSceneEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static cn.hutool.core.util.RandomUtil.randomInt;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberUserAuthServiceImpl implements MemberUserAuthService {
    public static final String SMS_CODE_CACHE_PREFIX = "sms:code:";
    private final SmsCodeProperties smsCodeProperties;

    private final StringRedisTemplate redisTemplate;

    @Override
    public Boolean sendSmsCode(AppAuthSmsSendReqVO reqVO) {
        SmsSceneEnum sceneEnum = SmsSceneEnum.getCodeByScene(reqVO.getScene());
        Assert.notNull(sceneEnum, "验证码场景({}) 查找不到配置", reqVO.getScene());



        // 创建验证码记录
        String code = String.valueOf(randomInt(smsCodeProperties.getBeginCode(), smsCodeProperties.getEndCode() + 1));
        //
        String redisCode = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + reqVO.getMobile());
        if (StringUtils.isNotEmpty(redisCode)) {
            long time = Long.parseLong(redisCode.split("-")[1]);
            //60s内不能再发
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "第三方认证平台获取客户编号异常!");
        }
        //存入redis
        redisTemplate.opsForValue().set(SMS_CODE_CACHE_PREFIX + reqVO.getMobile(),
                code + "-" + System.currentTimeMillis());

        //发送短信验证码


        return null;
    }
}
